package com.heima.user.service.impl;


import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        IPage<ApUserRealname> pageParam=new Page<>(dto.getPage(),dto.getSize());

        LambdaQueryWrapper<ApUserRealname> query=new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            query.eq(ApUserRealname::getStatus,dto.getStatus());

        }
        IPage<ApUserRealname> pageResult = page(pageParam, query);


        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }

    /**
     * 根据状态进行审核
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateStatusById(AuthDto dto, Short  status) {
        //1 检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询ApUserRealname
        ApUserRealname userRealname = getById(dto.getId());
        if (userRealname == null || userRealname.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2 获取apUser id
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser == null || apUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.APUSER_STATUS_ERROR);
        }
        //3 修改状态2 9
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        // 拒绝原因
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);


        //4 如果审核通过
        if (status.intValue() == AdminConstants.PASS_AUTH.intValue()) {
            //4.1 远程创建自媒体账号
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null || wmUser.getId()==null) {
                CustException.cust(AppHttpCodeEnum. WMUSER_NOT_EXIT);
            }

            //4.2 远程创建作者账号
            boolean flag = createApAuthor(wmUser);
            if (!flag) {
                CustException.cust( AppHttpCodeEnum.AUTHOR_ADD_ERROR );
            }

            //5 更新APUser数据中 flag=1
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }

//        int i = 1 / 0;

        //6 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 远程调用：新增作者
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
        boolean flag = false;

        ApAuthor author = articleFeign.findByUserId(wmUser.getApUserId());
        if (author == null) {

            author = new ApAuthor();
            author.setCreatedTime(new Date());
            author.setName(wmUser.getName());
            author.setType(AdminConstants.AUTHOR_TYPE);
            author.setUserId(wmUser.getApUserId());
            author.setWmUserId(wmUser.getId());
            ResponseResult result = articleFeign.save(author);

            // 判断成功执行
            if (result.getCode() == 0) {
                flag = true;
            }
        }


        return flag;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 创建自媒体账号
     * @param dto
     * @param apUser
     * @return
     */
    private WmUser createWmUser(AuthDto dto, ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());

        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setImage(apUser.getImage());
            wmUser.setName(apUser.getName());
            wmUser.setNickname(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setScore(100);
            wmUser.setStatus(9);
            wmUser.setType(0);

            // 成功后携带主键返回
            return wemediaFeign.save(wmUser);
        }

        return null;

    }


}